<script lang="tsx">
import { Skeleton } from '~/components/skeleton';
import { noticeMeta } from '~/composables/useMeta';
import { divPrecision } from '~/utils';
import SelectToken from './SelectToken.vue';

type TWithdrawBody = NonNullable<Api.GetParam<typeof apis.apiFundWithdrawSubmit>['requestBody']>;

export function LoadingComponent() {
  return (
    <Skeleton class="grid grid-cols-2 gap-3">
      <Skeleton type="rect" width="auto" />
      <Skeleton type="rect" width="auto" />
      <Skeleton class="col-span-full" type="rect" width="auto" />
      <Skeleton type="rect" width="auto" />
      <Skeleton type="rect" width="auto" />
      <Skeleton class="col-span-full" type="text" length={50} />
      <Skeleton class="col-span-full" type="rect" width="auto" />
      <Skeleton class="col-span-full" type="text" length={8} />
    </Skeleton>
  );
}
</script>

<script setup lang="tsx">
const userStore = useUserStore();
const currencyStore = useCurrencyStore();

const withdrawReadyQry = useQuery({
  queryKey: [apis.apiFundWithdrawReady.id],
  queryFn: () => apis.apiFundWithdrawReady(undefined),
  gcTime: 0,
});
const withdrawData = computed(() => withdrawReadyQry.data.value);
const withdrawMut = useMutation({
  mutationKey: [apis.apiFundWithdrawSubmit.id],
  mutationFn: apis.apiFundWithdrawSubmit.setDefaultConfig({ successMessage: false }),
  onSuccess: (resp) => {
    currencyStore.refetch();
    noticeMeta().withdraw({ currency: resp.currency.currency, id: resp.address });
    antdModal.success({
      content: '预计24小时内到账',
      class: 'ant-cover__confirm-modal',
      okCancel: false,
    });
    globalPopups.wallet.close();
  },
});

// #region 币种信息
const currencyList = computed(() => withdrawData.value?.currency_balance_list);
const currency = computed(() => {
  const targetCurrency = currencyList.value?.find(item => item.currency === withdrawForm.state.currency);
  if (!targetCurrency)
    return;

  return {
    ...targetCurrency,
    token: targetCurrency.tokens?.find(item => item.chain === withdrawForm.state.chain),
  };
});
// 最小提款金额（小数值）
const minWithdrawAmount = computed(() => divPrecision(currency.value?.token?.min_withdraw_amount ?? 0, currency.value?.token?.decimal));

watch(currencyList, (val) => {
  if (val) {
    withdrawForm.state.currency = val[0].currency;
    withdrawForm.state.chain = val[0].tokens?.[0].chain ?? '';
  }
}, { immediate: true });
// #endregion

const withdrawForm = useAntdForm<TWithdrawBody>({
  currency: { value: '' },
  chain: { value: '' },
  address: {
    value: '',
    rules: [{ validator(_, value) {
      if (!value) {
        return formResult($t('1mZrq1hNqQ7JTeeG6z3Hc'));
      }

      return formResult();
    } }],
  },
  amount: {
    value: '',
    rules: [{ validator(_, value) {
      const bnVal = bignumber(value);
      const _currency = currency.value!;

      if (bnVal.isNaN())
        return formResult($t('hWstS1hvXUnYtJxNPnio'));

      if (bnVal.gt(_currency.balance))
        return formResult($t('oGiAq6Hya7nrnOzZfduQr'));

      if (bnVal.lt(minWithdrawAmount.value))
        return formResult($t('a7Cxbcr5Epsbbn3Xxd8nh'));

      return formResult();
    } }],
  },
  security_code: { value: '' },
});

// TODO: 服务费计算
const serviceAmount = computed(() => {
  const _amount = withdrawForm.state.amount;
  const _chain = currency.value?.token;

  if (!_amount || !_chain)
    return bignumber(0);

  const amountBn = bignumber(_amount);
  let serviceAmount = bignumber(_chain.service_amount);
  const minServiceAmount = bignumber(_chain.min_service_amount);
  const maxServiceAmount = bignumber(_chain.max_service_amount);

  if (serviceAmount.lte(0)) {
    serviceAmount = amountBn.times(_chain.service_amount_rate);
  }
  if (serviceAmount.lt(minServiceAmount)) {
    serviceAmount = minServiceAmount;
  }
  if (serviceAmount.gt(maxServiceAmount)) {
    serviceAmount = maxServiceAmount;
  }

  return serviceAmount;
});

async function handleSubmit() {
  const res = userStore.verified?.authenticator ? await openAuthFlowPopup('verify2FA').catch(() => undefined) : {};
  withdrawMut.mutate({ requestBody: {
    ...withdrawForm.state,
    amount: String(withdrawForm.state.amount),
    security_code: res?.security_code || '',
  } });
}

onActivated(() => {
  withdrawReadyQry.refetch();
});

await withdrawReadyQry.suspense();
</script>

<template>
  <div class="">
    <AForm v-bind="withdrawForm.props" @finish="handleSubmit">
      <!-- 币/链选择 -->
      <AFormItem class="mb-3">
        <SelectToken
          v-model:currency="withdrawForm.state.currency"
          v-model:chain="withdrawForm.state.chain"
          :list="currencyList"
        />
      </AFormItem>

      <!-- 提款地址 -->
      <AFormItem v-bind="withdrawForm.itemProps.address" class="mb-3">
        <AInput
          v-model:value="withdrawForm.state.address" allowClear
          :placeholder="$t('1mZrq1hNqQ7JTeeG6z3Hc')"
        />
      </AFormItem>

      <!-- 提款金额 -->
      <AFormItem v-bind="withdrawForm.itemProps.amount">
        <div class="flex">
          <AInputNumber
            v-model:value="withdrawForm.state.amount" class="w-full flex-1"
            :controls="false" :placeholder="$t('qlxJcfsbDcKdovNZpjeKl')"
          />
          <div class="grid grid-cols-[auto_1fr] ml-3 box-border flex-1 content-center rounded-2 bg-sys-layer-a px-3 text-sm lh-1.1em">
            <TCurrencyIcon class="row-span-2 mr-2 self-center" :symbol="currency?.currency" />
            <span class="text-sys-text-body">{{ currency?.currency }}</span>
            <TNum :value="currency?.balance ?? 0" format="pad-dec" :decimals="6" weakPad />
          </div>
        </div>
      </AFormItem>

      <div class="text-sys-text-body">
        {{ withdrawData?.tips }}
      </div>
      <div class="mb-4 mt-2 text-sys-text-body">
        <i class="i-local:warning text-1.2em" />
        {{ $t('vyfKcRCgW7fSsPqvAqhF') }} {{ currency?.token?.min_withdraw_amount }} {{ currency?.token?.chain }}
      </div>

      <AButton
        class="ant-cover__Button-3d-primary mt-auto"
        type="primary" block htmlType="submit"
        :loading="withdrawMut.isPending.value"
        :disabled="withdrawMut.isPending.value"
      >
        {{ $t('xQp2HJedTncmCsXifzn3') }}
      </AButton>
      <div v-if="serviceAmount.gt(0)" class="mt-2 text-sys-text-body">
        {{ $t('d21YkSuaBcGeTpDFPyg') }} ≈  {{ serviceAmount.toFormat(2) }} {{ currency?.token?.currency }}
      </div>
    </AForm>
  </div>
</template>
